<?php

class ETidy extends COutputProcessor {

    private $config = array('clean' => true, 'show-body-only' => true,);
    private $encoding = 'utf8';

    public function setEncoding($value) {
        $v = strtolower($value);
        if(!in_array($v, array('ascii', 'latin0', 'latin1', 'raw', 'utf8', 'iso2022', 'mac', 'win1252', 'ibm858', 'utf16', 'utf16le', 'utf16be', 'big5', 'shiftjis'))) throw new CException(Yii::t('ETidy', '"{value}" is not a valid encoding.', array('{value}' => $value)));
        $this->encoding = $v;
    }

    public function getEncoding() {
        return $this->encoding;
    }

    public function setConfig($value) {
        if(!is_array($value) && !is_string($value)) throw new CException(Yii::t('ETidy', '"{value}" is not a string nor an array. Invalid configuration.', array('{value}' => $value)));
        if(is_string($value) && !is_readable($value)) throw new CException(Yii::t('ETidy', 'Cannot read Tidy configuration file.'));
        $this->config = $value;
    }

    public function getConfig() {
        return $this->config;
    }

    public function processOutput($output) {
        $output = $this->cleanRepair($output);
        parent::processOutput($output);
    }

    public function cleanRepair($content) {
        if(function_exists('tidy_repair_string')) {
            return @tidy_repair_string($content, $this->config, $this->encoding);
        }
        return $content;
    }
}
